import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Servlet extends HttpServlet{
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		List<String> listName = getListName();
		for (int i=0; i<listName.size(); ++i){
			out.println(listName.get(i) + "<br/>");
			//out.println(listName.get(i));
		}
//		
//		request.setAttribute("ListName", listName);
//		request.getRequestDispatcher("index.jsp").forward(request, response);
	}
	
	public static Connection openConnection()
	{
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "user";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root"; 
		String password = "12345";
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url + dbName,userName,password);
			System.out.println("Connected to the database");
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		  
		return conn;
	}
	
	public List<String> getListName()
	{
		Connection conn = null;
		Vector<String> rs = null;
		ResultSet rsSet = null;
		Statement st = null;
		try {
			conn = openConnection();
			String sql = "select * from user;";
			st = conn.createStatement();
			rsSet = st.executeQuery(sql);
			rs = new Vector<String>();
			while (rsSet.next()) {
				String temp = rsSet.getString(1);
				rs.add(rsSet.getString(1));
				System.out.println(temp);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return rs;
	}
}
